import React, {PureComponent} from 'react';
import {View, Animated, Button, Text, ToastAndroid} from 'react-native';

export default class Block extends PureComponent {
  opacity = 0;
  speed = 0.01;
  animationFrame: any = null;
  box: any = null;

  // 模拟 JS 被占用
  blockJS = () => {
    const start = Date.now();
    ToastAndroid.show('开始阻塞', 0.5);
    while (Date.now() - start < 1000) {
      // 空循环，占用 1000ms JS
    }
    ToastAndroid.show('结束阻塞', 0.5);
  };

  runAnimation = () => {
    this.opacity += this.speed;
    if (this.opacity > 1) this.opacity = 1;
    if (this.opacity < 0) this.opacity = 0;

    this.box?.setNativeProps({
      style: {
        opacity: this.opacity,
        transform: [{scale: this.opacity}],
      },
    });

    this.animationFrame = requestAnimationFrame(this.runAnimation);
  };

  startAnimation = () => {
    setTimeout(() => {
      this.blockJS();
    }, 500);
    this.runAnimation();
  };

  render() {
    return (
      <View style={{flex: 1}}>
        <Text>阻塞</Text>
        <Animated.View
          ref={ref => (this.box = ref)}
          style={{width: 200, height: 200, backgroundColor: 'blue', opacity: 0}}
        />
        <Button title="开始动画" onPress={this.startAnimation} />
        <Button title="模拟JS阻塞" onPress={this.blockJS} />
      </View>
    );
  }
}
